package com.bc.plugin.doc.resolver.help;

import com.power.common.util.StringUtil;
import com.power.doc.constants.DocGlobalConstants;
import com.power.doc.constants.DocTags;
import com.power.doc.model.ApiParam;
import com.power.doc.utils.DocClassUtil;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;

import java.util.List;

public class ApiParamHelper {

    public static ApiParam newApiParam(String primitiveClassName, int level) {
        if (DocGlobalConstants.JAVA_OBJECT_FULLY.equals(primitiveClassName)) {
            ApiParam param = ApiParam.of().setLevel(level).setField("any object").setType("object");
            param.setDesc(DocGlobalConstants.ANY_OBJECT_MSG)
                    .setVersion(DocGlobalConstants.DEFAULT_VERSION);
            return param;
        } else {
            String typeName = DocClassUtil.getSimpleName(primitiveClassName);
            StringBuilder comments = new StringBuilder();
            comments.append("The api directly returns the ").append(typeName).append(" type value.");
            ApiParam apiParam = ApiParam.of().setField("no param name").setType(typeName).setDesc(comments.toString())
                    .setVersion(DocGlobalConstants.DEFAULT_VERSION);
            return apiParam;
        }
    }

    public static ApiParam newApiParam(JavaField field, String genericType, int level) {
        JavaClass javaClass = field.getType();
        String typeSimpleName = javaClass.getSimpleName().toLowerCase();
        if (genericType != null) {
            typeSimpleName = genericType;
        }
        String processedType = DocClassUtil.processTypeNameForParams(typeSimpleName);
        String comment = field.getComment();
        if (javaClass.isEnum()) {
            String enumComments = javaClass.getComment();
            if (StringUtil.isNotEmpty(enumComments)) {
                comment = comment + "(See: " + enumComments + ")";
            }
        }
        List<DocletTag> paramTags = field.getTags();
        String since = DocGlobalConstants.DEFAULT_VERSION;// since tag value
        boolean isRequired = false;
        for (DocletTag docletTag : paramTags) {
            if (DocClassUtil.isRequiredTag(docletTag.getName())) {
                isRequired = true;
            }
            if (DocTags.SINCE.equals(docletTag.getName())) {
                since = docletTag.getValue();
            }
        }
        ApiParam param = ApiParam.of()
                .setVersion(since)
                .setRequired(isRequired)
                .setLevel(level)
                .setField(field.getName())
                .setDesc(comment)
                .setType(processedType);
        return param;
    }

    public static ApiParam newApiParam(JavaField field, int level) {
        return newApiParam(field, null, level);
    }
}
